import api from '../../../api/index';
import dayjs from '../../../plugin/dayjs/index';
import daysbefore from '../../../plugin/daysbefore';
import * as echarts from '../../../components/ec-canvas/echarts';
const {
  QNMPPlugin,
} = requirePlugin('QNBleApi');
// import getReports from '@yolanda-qn/four-electrodes-report-lib-pe';
import {
  sealGenderParam,
  formatDate,
  formatTimeValue
} from '../../utils/util';

const APPID = 'LAIKANG20231106';
 /**
   * 微信的本地日志功能，需要用户手动反馈才能拿到日志文件
   */
 const logger = () => {
  const wxlogger =
    wx.getLogManager &&
    wx.getLogManager({
      level: 0,
    });
  const log = (...params) => {
    // console.log(...params)
    wxlogger && wxlogger.log(...params);
  };
  return {
    log,
  };
};
//全局声明chart
var seriesDataArr = [];
var timeArr = [];
var chart = null;
let bleApi = null

// 时间格式化
function formatTime(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}
function formatTime2(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD');
}
Page({
	/**
   * 页面的初始数据
   */
	data: {
    showDialogdevice: false,
		inputshow: false,
    deviceResultItems: [],
		inputlist: [ { unit: '身高', value: '', text: '请输入身高' },{ unit: '体重', value: '', text: '请输入体重' } ],
		c_val: 80,
		shebeiicon: 'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/%E8%BA%AB%E9%AB%98%E4%BD%93%E9%87%8D.png',
		fasleshebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/gantanhao.png',
    heightValueLast: '--',
    weightValueLast: '--',
    bmiValueLast: '--',
    linedata: null,
    show: false,
		showDialog: false,
		bindDeviceTextInfo: '',
    ec: {
      // 初始化图表
      onInit:  (canvas, width, height) => {
        //初始化echarts元素，绑定到全局变量，方便更改数据
        chart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        canvas.setChart(chart);
        return chart;
      }
    },
    age: 30,
    // 1 男 0 女
    gender: 1,
    height: 170,
    unit: 'kg',
    isSport: false,
    realTimeWeight: 0,
    bleState: '空闲',
    state: 'paused',
    measureData: null,
    eightMeasureData: null,
    score: 0,
    // 蓝牙是否可用
    available: false,
    // 发现设备中
    discovering: false,
    // 是否已连接
    connected: false,
    // 是否正在连接
    connecting: false,
    // 存储数据
    storedData: [],
    offlineDataCount: 0,
    fatherHeight: 0,
    motherHeight: 0,
    useTeenagerAlgorithm: false,
    heightValue: '--',
    weightValue: '--',
    bmiValue: '--',
    searchDevice: [],
    available: false,
    bodyShapeList: ["无体型值", "隐形肥胖型", "运动不足型",
    "偏瘦型", "标准型", "偏瘦肌肉型", "肥胖型", "偏胖型", "标准肌肉型", "非常肌肉型"]
	},

	/**
   * 生命周期函数--监听页面加载
   */
	onLoad(options) {
    console.log('onLoad')
		// this.drawProgress()
    this.setData({
      showDialogdevice: false
     })
		this.gethistrorylist(); //查看历史数据
    this.getloadlist(); //查询当前最新数据
  },
  onShow() {
    console.log('onShow')
    this.initBlueTooth()
    this.setData({
      showDialogdevice: false
     })
  },
  initBlueTooth () {
    wx.openBluetoothAdapter({
      success: res => {
        console.log('初始化蓝牙模块成功', res)
        this.setData({
          available: true
        })
        this.doBluetoothAdapterStateChange()
        this.get()
      },
      fail: err => {
        console.log('初始化蓝牙模块失败', err)
        this.doBluetoothAdapterStateChange()
        this.setData({
					available: false
				})
      }
    })
  },
  doBluetoothAdapterStateChange() {
		wx.onBluetoothAdapterStateChange((res) => {
			console.log('蓝牙状态', res)
			if (res.available) {
				this.setData({
					available: true
				})
        // this.get()
			} else {
				this.setData({
					available: false
				})
			}
		})
	},
  async get() {
    this.setData({
      showDialogdevice: false
     })
		try {
			this.setData({
				loading: true
			})
		  const res = await api.post('/api/user/storage/get', {
			data: {
			  'key': 'devicelist'
			}
		  })
		  if(res[0].value) {
				var array = JSON.parse(res[0].value)
				const listValue = array.filter(item => item.name === 'heightbody')
				if(listValue.length > 0 && listValue[0].devicelist.length > 0) {
          // 如果绑定的有设备，直接连接
          this.initBLE()
				} else {
          this.setData({
           showDialogdevice: true
          })
        }
		  } else {
        this.setData({
         showDialogdevice: true
        })
         }
			this.setData({
				loading: false
			})
		} catch (e) {
		  console.log('get->', e)
		  return null
		}
	},
  gohistorypage() {
    this.stopBle()
		wx.navigateTo({
			url: `/heightfat/pages/history/index`,
		  })
  },
  goDetailpage () {
    let id = this.data.detailId
    console.log(id);
    wx.navigateTo({
          url: `/heightfat/pages/detail/index?id=${id}`,
        })
  },
  initBLE() {
    console.log('初始化蓝牙开始')

    // 初始化蓝牙
    bleApi = new QNMPPlugin({
      appId: APPID, // 必须, 客户小程序的appid, 需要配置才能使用，
      mpwx: wx, // 非必须 连接广播称时需要
      logger: logger(), // 非必须，日志功能，最好有，方便排查问题，可以替换为客户自己的
      useTeenagerAlgorithm: this.data.useTeenagerAlgorithm // 开启青少年算法，开启后，小于18岁青少年会展示青少年算法
    });
    console.log(bleApi,'初始化蓝牙成功')
    // 错误监听
    bleApi.onError = (err) => {
      console.log('捕捉到错误', err);
      if(err.detail.code === 'OPEN_BLE_ADAPTER_FAILED') {
        this.setData({
          bindDeviceTextInfo: '蓝牙未开启，请开启蓝牙'
        })
        this.setData({
          showDialog: true
        })
      }
    };

    // 初始化回调
    bleApi.onReady = ({
      bleEnableState, //表示当前蓝牙是否为开启状态
    }) => {
      console.log(bleEnableState,'bleEnableState')
      if (bleEnableState) {
        // this.get()
        bleApi.startBleDeviceDiscovery();
      } else {
        console.log('蓝牙状态为关闭');
        this.setData({
          bindDeviceTextInfo: '蓝牙未开启，请开启蓝牙'
        })
        this.setData({
          showDialog: true
        })
      }
    };

    // 设置蓝牙监听事件
    bleApi.setBleEventListener(this.bleEventListener());

    // 初始化
    bleApi.init();
  },
  /**
     * 停止蓝牙活动
     */
  // stopBle: async function () {
  //   console.log(bleApi, '停止蓝牙活动');
  //   await bleApi.stop();
  //   await bleApi.releaseBleSource();
  // },
  async stopBle () {
    console.log(bleApi, '停止蓝牙活动22');
    if (bleApi) {
      await bleApi.stop();
      await bleApi.releaseBleSource();
    }
  },
  getSearchDevice() {
		return this.data.searchDevice
	},
  /**
     * 刷新蓝牙
     */
  restart() {
    console.log('开始搜索设备')
    // bleApi
    //   .stop()
    //   .then(() => {
    //     this.setData({
    //       connected: false,
    //     });
    //     bleApi.startBleDeviceDiscovery();
    //   })
    //   .catch((err) => {
    //     console.log('停止扫描失败', err);
    //   });
    // bleApi.startBleDeviceDiscovery();
    this.initBLE()
  },

  async handlerConnect(device) {
    console.log(device,'设备连接')
		this.setData({
			bindDeviceTextInfo: '连接设备中...'
		})
    this.setData({
			showDialog: true
		})
    const {
      height,
      gender,
      age,
      unit,
      connected,
      isSport,
      motherHeight,
      fatherHeight
    } = this.data;
    if (this.connecting || connected) {
      console.log('当前正在连接，不再处理');
      return;
    }
    this.connecting = true;
    const birthday = new Date();
    birthday.setFullYear(birthday.getFullYear() - age);
    const user = {
      height,
      gender: sealGenderParam(gender),
      birthday: formatDate(birthday),
      isSport, // 是否是运动员模式
      fatherHeight,
      motherHeight
    };
    console.log(user, 'user')
    console.log(unit, 'unit')
    /**
     * 调用连接成功后，会返回本次连接的设备访问对象，可以对设备进行一些蓝牙数据通讯
     * 每次连接返回的都不一样，连接成功后，该对象开始可以操作，连接失败或断开后，该对象会失效
     */
    console.log('要连接的对象', device);
    this.setData({
      offlineDataCount: device.offlineDataCount
    });
    this.deviceHandler = await bleApi.createBleConnection(device, this.deviceEventListener(), {
      user,
      unit,
    });
  },

  // 蓝牙相关事件回调
  bleEventListener() {
    /**
     * 监听扫描到设备的回调
     */
    const onBleDeviceFound = (device) => {
      this.setData({
        searchDevice: [device]
      })
      this.handlerConnect(device);
    };

    /**
     * 监听蓝牙断开连接的回调
     */
    const onDisconnected = (device) => {
      // this.updateState('设备连接已断开');
      this.setData({
        connected: false,
        state: 'paused',
        connecting: false,
      });
      this.connecting = false;
      this.connected = false;
      console.log('设备连接已断开', device);
    };

    /**
     * 监听蓝牙状态发生变化回调，连接成功或断开连接都会出触发
     */
    const onBluetoothEnableChange = ({
      available
    }) => {
      if (available) {
        // this.updateState('蓝牙可用，空闲');
        this.setData({
          bindDeviceTextInfo: '蓝牙可用，空闲'
        })
        bleApi.startBleDeviceDiscovery();
      } else {
        this.setData({
          bindDeviceTextInfo: '蓝牙不可用'
        })
        setTimeout(() => {
          this.setData({
            showDialog: false
          })
        }, 500);
      }
      this.setData({
        available,
      });
    };

    /**
     * 	监听设备连接成功回调
     */
    const onConnected = (device) => {
      // this.updateState('已连接');
      this.setData({
        bindDeviceTextInfo: '设备已连接'
      })
      console.log('设备已连接', device);
      this.connecting = false;
      this.setData({
        connected: true,
        state: 'running',
        device,
      });
    };

    /**
     * 监听停止扫描的回调
     */
    const onStopDiscoveryDevice = () => {
      // this.updateState('已停止扫描');
      this.setData({
        discovering: false,
      });
    };

    /**
     * 监听开始扫描设备的回调
     */
    const onStartDiscoveryDevice = () => {
      // this.updateState('开始扫描');
      this.setData({
        bindDeviceTextInfo: '开始扫描设备'
      })
      this.setData({
        devices: [],
        discovering: true,
        offlineDataCount: 0,
      });
    };

    return {
      onBleDeviceFound,
      onDisconnected,
      onBluetoothEnableChange,
      onConnected,
      onStopDiscoveryDevice,
      onStartDiscoveryDevice,
    };
  },

  // 秤端相关事件回调
  deviceEventListener() {
    /**
     * 实时测量体重
     */
    const onGetUnsteadyWeight = ({
      weight
    }) => {
      // this.updateState('测量中');
      this.setData({
        bindDeviceTextInfo: '正在测量中'
      })
      this.setData({
        realTimeWeight: weight,
        state: 'running',
        unit: 'kg',
      });
    };
    /**
     * 获取到了实时的稳定测量数据，在连接APP的情况下，进行测量，数据会进入到这个回调
     * @param {object} measure 体脂秤测量数据
     */
    const onGetScaleData = ({
      measure
    }) => {
      // this.updateState('测量完成');

      console.log('测量结束', measure);
      this.analysisData(measure);
    };

    const onGetTeenagerData = (data) => {
      // this.updateState('测量完成');
      console.log('测量结束', data);
      this.setData({
        bindDeviceTextInfo: '测量完成'
      })
      // wx.navigateTo({
      //   url: `/pages/cp30b/teenagerReport/index?measureData=${JSON.stringify(data)}`,
      // })
    }

    /**
     * 身高秤测量实时身高的回调
     */
    const onGetUnsteadyHeight = ({
      height
    }) => {
      if (height <= 0) return;
      this.setData({
        realTimeHeight: height,
        state: 'running',
        unit: 'cm',
      });
    };

    /**
     * 身高秤测量身高结束的回调
     */
    const onMeasureHeightEnd = ({
      weight,
      height
    }) => {
      this.setData({
        realTimeWeight: weight,
        realTimeHeight: height,
        state: 'running',
        unit: 'cm',
      });
    };
    /**
     * 请求算法接口错误回调，一般是因为用户信息的参数错误导致
     */
    const onFetchScaleDataFail = (err) => {
      console.error('请求算法接口出错了', err);
    };

    // 普通四电极蓝牙秤存储数据
    const onGetNormalBleScaleStoredData = (payload) => {
      payload.data.time = formatTimeValue(new Date(payload.data.time));
      console.info('onGetNormalBleScaleStoredData', payload);
      this.data.storedData.push(payload.data);
      this.setData({
        storedData: this.data.storedData,
      });
    };

    return {
      onGetUnsteadyWeight,
      onGetScaleData,
      onGetUnsteadyHeight,
      onMeasureHeightEnd,
      onMeasureHeightEnd,
      onFetchScaleDataFail,
      onGetNormalBleScaleStoredData,
      onGetTeenagerData
    };
  },

  /**
   * 处理测量后的数据, 根据设备类型调用不同的处理方法
   */
  analysisData(scaleData) {
    this.analysisNormalData(scaleData);
  },
  /**
   * 展示普通秤测量后的数据，仅供参考，
   */
  analysisNormalData(scaleData) {
    // 配置信息
    const config = {
      weightUnit: 'kg', // 重量单位
      lang: 'zh_CN', // 当前系统语言
    };
    const measureData = {
      ...scaleData.user,
      ...scaleData,
    }
    console.log('构造前', measureData);
    // 这里只是拿到kg数据，尚未进行单位转换和小数位精度fixed处理
    // const reports = getReports(measureData, config)
    //   // 可以使用order字段来排序
    //   .sort((a, b) => a.order - b.order)
    //   // toObject会进行单位转换和小数位精度处理，返回的是string类型，不应该使用这里的数据来进行额外计算
    //   .map((item) => item.toObject());
    this.setData({
      realTimeWeight: 0,
      realTimeHeight: 0,
      state: 'paused',
      score: scaleData.score,
      measureData: measureData,
      heightValue: Number(measureData.height).toFixed(1),
      weightValue: Number(measureData.weight).toFixed(1),
      bmiValue: Number(measureData.bmi).toFixed(1),
    });
    this.setData({
			'inputlist[0].value': this.data.heightValue,
			'inputlist[1].value': this.data.weightValue,
		});

    let deviceResultItems = [
      {
        "code": "XYZBXY001013",
        "deviceBrand": null,
        "deviceCode": "surveyinginstrument",
        "deviceNo": null,
        "value": measureData.height
      },
      {
        "code": "XYZBXY001007",
        "deviceBrand": null,
        "deviceCode": "surveyinginstrument",
        "deviceNo": null,
        "value": measureData.weight
      },
      {
        "code": "XYZBXY001001",
        "deviceBrand": null,
        "deviceCode": "surveyinginstrument",
        "deviceNo": null,
        "value": measureData.bmi
      },
      {
        "code": "lk1590141731679",
        "deviceBrand": null,
        "deviceCode": "surveyinginstrument",
        "deviceNo": null,
        "value": measureData.bodyfat
      },
      {
        "code": "XYZBXY001029",
        "deviceBrand": null,
        "deviceCode": "surveyinginstrument",
        "deviceNo": null,
        "value": measureData.water
      },
      {
        "code": "HXJK00000002",
        "deviceBrand": null,
        "deviceCode": "surveyinginstrument",
        "deviceNo": null,
        "value": measureData.muscle
      },
      {
        "code": "HXJK00000009",
        "deviceBrand": null,
        "deviceCode": "surveyinginstrument",
        "deviceNo": null,
        "value": measureData.muscleMass
      },
      {
        "code": "XYZBXY001033",
        "deviceBrand": null,
        "deviceCode": "surveyinginstrument",
        "deviceNo": null,
        "value": measureData.bone
      },
      {
        "code": "HXJK00000006",
        "deviceBrand": null,
        "deviceCode": "surveyinginstrument",
        "deviceNo": null,
        "value": measureData.lbm
      },
      {
        "code": "lk1636612991835",
        "deviceBrand": null,
        "deviceCode": "surveyinginstrument",
        "deviceNo": null,
        "value": measureData.protein
      },
      {
        "code": "HXJK00000001",
        "deviceBrand": null,
        "deviceCode": "surveyinginstrument",
        "deviceNo": null,
        "value": measureData.subfat
      },
      {
        "code": "XYZBXY001035",
        "deviceBrand": null,
        "deviceCode": "surveyinginstrument",
        "deviceNo": null,
        "value": Number(measureData.visfat).toFixed(0)
      },
      {
        "code": "HXJK00000003",
        "deviceBrand": null,
        "deviceCode": "surveyinginstrument",
        "deviceNo": null,
        "value": Number(measureData.bodyAge).toFixed(0)
      },
      {
        "code": "HXJK00000014",
        "deviceBrand": null,
        "deviceCode": "surveyinginstrument",
        "deviceNo": null,
        "value": this.data.bodyShapeList[Number(measureData.bodyShape)]
      },
      {
        "code": "lk1590141731918",
        "deviceBrand": null,
        "deviceCode": "surveyinginstrument",
        "deviceNo": null,
        "value": Number(measureData.bmr).toFixed(0)
      }
    ]

    this.setData({
      deviceResultItems
    })
    this.saveNickname()
    this.setData({
      bindDeviceTextInfo: '测量完成'
    })
    setTimeout(() => {
      this.setData({
        showDialog: false
      })
    }, 500);
  },
  getWeekDays() {
		let dates = []
		for (var i = 365; i >= 0; i--) {
			var currentDate = new Date();
			currentDate.setDate(currentDate.getDate() - i);
			var month = ("0" + (currentDate.getMonth() + 1)).slice(-2);
			var day = ("0" + currentDate.getDate()).slice(-2);
			var formattedDate = month + "/" + day;
			dates.push(formattedDate);
		}
		return dates
	},
	gethistrorylist() {
		api
			.post('/api/hxhealth/exams/records', {
				data: {
					everyday: true,
					itemcode: 'XYZBXY001007',
					typecode: 'surveyinginstrument',
					everyday: true
				},
        head: {
					firstresult: 0,
					maxresults: 1000,
					bodytype: 'flat',
				}
			})
			.then((res) => {
				// console.log(res);
				console.log('----历史数据----', res);
				if (res.length > 0) {
					const jsonData = res;
					// 提取数据的数组
					const values = [];
					const times = [];

					// 遍历 body 数组
					jsonData.forEach((entry) => {
						// 遍历 devices 数组
						entry.devices.forEach((device) => {
							console.log(device);
							// 找到 code 为 "XYZBXY001013" 的项
							const item = device.items.find((item) => item.code === 'XYZBXY001007');

							// 如果找到了，将 value 和 time 添加到相应的数组中
							if (item) {
								console.log(item);
								values.push(Number(item.value)); // 将值转换为数字类型
								times.push(entry.time.slice(0, 10).replace(/-/g, '/'));
							}
						});
					});
					const linedata = {
						values,
						times
					};
          console.log(linedata);
          this.setData({
            linedata
          });
          // 模拟获取接口数据
    setTimeout(() => {
      this.getEchartData(linedata)
    }, 1000);
				} else {
					const linedata = {
						values: [],
						times: this.getWeekDays()
					};
					this.setData({
						linedata
					});
					// 模拟获取接口数据
					setTimeout(() => {
						this.getEchartData(linedata);
					}, 1000);
				}
			});
	},
	getloadlist() {
		// 整体列表查询
		api
			.post('/api/exams/lastvalues', {
				data: {
					devkind: 'surveyinginstrument',
					devmode: '',
					itemcode: '',
					typecode: '',
					unionuser: true
				}
			})
			.then((res) => {
        // console.log(res);
        this.setData({
					newtime: res[0].examtime
				});
				console.log('----最新数据----', res);
				const array = res;
				for (let y = 0; y < array.length; y++) {
					if (array[y].code == 'XYZBXY001013') {
						this.setData({
							heightValueLast: Number(array[y].value).toFixed(1)
						});
					}
					if (array[y].code == 'XYZBXY001007') {
						this.setData({
							weightValueLast: Number(array[y].value).toFixed(1)
						});
          }
          if (array[y].code == 'XYZBXY001001') {
						this.setData({
							bmiValueLast: Number(array[y].value).toFixed(1)
						});
					}
				}
			});
	},
	savedevices() {
    let itemsList = []
    if (this.data.inputshow) {
      // 手动录入
      itemsList = [
        {
          code: 'XYZBXY001013',
          checkDate: null,
          level: null,
          value: this.data.inputlist[0].value?this.data.inputlist[0].value:this.data.heightValue,
          deviceBrand: '',
          deviceNo: ''
        },
        {
          code: 'XYZBXY001007',
          checkDate: null,
          level: null,
          value: this.data.inputlist[1].value?this.data.inputlist[1].value:this.data.weightValue,
          deviceBrand: '',
          deviceNo: ''
        }
      ]
    } else {
      // 设备测量获取结果
      itemsList = this.data.deviceResultItems
    }
		let data = {
			name: '运动监测',
			time: formatTime(),
			typecode: 'surveyinginstrument',
			typename: '运动监测',
			devices: [
				{
					name: '运动监测',
					kind: 'surveyinginstrument',
					items: itemsList
				}
			]
		};
		// 整体列表查询
		api
			.post('/api/hxhealth/exams/save', {
				data
			})
			.then((res) => {
				// console.log(res);
        console.log('----保存录入----', res);
        this.setData({
          detailId: res[0].id
        });
        this.closesaveNickname();
        this.gethistrorylist(); //查看历史数据
        this.getloadlist(); //查询当前最新数据
				wx.showToast({
					icon: 'none',
					title: '保存成功'
				});
			})
			.catch((e) => {
				console.log(e);
				wx.showToast({
					icon: 'none',
					title: e.faultstring ? e.faultstring : '保存失败'
				});
			});
	},
	openNickname() {
		this.setData({
			inputshow: true
		});
	},
	closesaveNickname() {
		this.setData({
			inputshow: false
		});
	},
	userNameInput1(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[0].value': e.detail.value
		});
	},
	userNameInput2(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[1].value': e.detail.value
		});
  },
	saveNickname() {
		// console.log(this.data.inputlist);
		let cansave = true
		this.data.inputlist.forEach(item => {
			if(!item.value) {
				wx.showToast({
					title: '请输入数值',
					icon: 'none',
					duration: 2000
				})
				cansave = false
				return
			}
			if(!/^[0-9]+(\.[0-9])?$/.test(Number(item.value))) {
				wx.showToast({
					title: '请输入最多一位小数的数值',
					icon: 'none',
					duration: 2000
				})
				cansave = false
				return
			}
		})
		if(cansave) {
			this.savedevices();
		}
	},
	modal_click_Hidden() {
		this.setData({
			inputshow: false
		});
  },
    // 绘制图表
    runColumncCanva() {
      var option = {
        title: {
          // text: '次/分',
          textStyle: {
              fontSize: 9,
              color: '#666666'
          }
      },
        color: ['#37A2DA'],
        legend: {
          data: ['近一年体重变化趋势'],
          icon: 'circle',
          left: 0,
          itemWidth: 9,
          // itemStyle: {
          //     color: '#5BBF70'
          // },
          textStyle: {
              color: '#333333',
              fontSize: 20
          }
      },
        grid: {
          left: '0%',
          right: '5%',
          bottom: 0,
          top: '15%',
          containLabel: true,
          show: true
      },

        tooltip: {
          show: true,
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: timeArr,
          axisLabel:{
            fontSize: 16,
            rotate: 0,//倾斜度 -90 至 90 默认为0
          }
        },
        yAxis: {
          type: 'value',
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          },
          axisLabel: {
            fontSize: 16
          }
        },
        series: seriesDataArr
      };
      //这里一定要做个charts是否存在的判断，因为万一ec那里没有初始化，这里就会报错
      if (chart) {
        chart.setOption(option);
        this.setData({
          show: true
        });
      }
    },
    getEchartData (linedata) {
      seriesDataArr = [{
        name: '近一年体重变化趋势',
        type: 'line',
        smooth: true,
        data: linedata.values
      }]
        timeArr = linedata.times
        this.runColumncCanva()
    },
    onCancel() {
      this.setData({
        showDialog: false,
      })
    },
	// 链接设备
	goBindEq() {
    // this.setData({
		// 	bindDeviceTextInfo: '正在初始化蓝牙设备'
		// })
		// this.setData({
		// 	showDialog: true
		// })
    // this.initBLE() // 蓝牙初始化
    wx.navigateTo({
			url: `/heightfat/pages/measurement/index?available=${this.data.available}`
		});
	},

	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function() {

	},

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() {
    console.log('onHide')
  },

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() {
    console.log('onUnload')
    this.stopBle()
  },

	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() {},

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() {},

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() {}
});
